package com.magina.antiPro.handler;


import javax.persistence.EntityNotFoundException;

import com.magina.antiPro.exception.BusinessException;
import com.magina.antiPro.response.Response;
import com.magina.antiPro.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.scheduling.config.Task;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.concurrent.ExecutionException;

@ControllerAdvice
@Slf4j
public class GobalExpectionHandler  {
    static final Log LOG = LogFactory.getLog(GobalExpectionHandler.class);

    private BusinessException businessException;
    public GobalExpectionHandler() {
    }

    public GobalExpectionHandler(BusinessException businessException) {
        this.businessException = businessException;
    }

    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseBody
    public Response<String> iae(Exception ex) {
        LOG.error("IllegalArgumentException", ex);
        ex.printStackTrace();
        return Response.fail("5000", ex.getMessage(),"IllegalArgumentException");
    }

    @ExceptionHandler({EntityNotFoundException.class})
    @ResponseBody
    public Response<String> enfe(EntityNotFoundException ex) {
        return Response.fail("4040", ex.toString());
    }

    @ExceptionHandler({BusinessException.class})
    @ResponseBody
    public Response<String> ae(BusinessException ex) {
        LOG.error("BusinessException", ex);
        return StringUtils.isEmpty(ex.getCode()) ? Response.fail(ex.getMessage()) : Response.fail(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Response<String> throwable(Exception exception) {
        if(exception instanceof ExecutionException){
            //捕获异步(有返回值)方法 抛出的执行异常
            log.error(exception.getCause().getMessage());
            exception.printStackTrace();
            return Response.fail("5998","magina_execution_error",exception.getCause().getMessage());
        }
        if(exception instanceof InterruptedException){
            //捕获异步(有返回值)方法 抛出的执行异常
            log.error(exception.getCause().getMessage());
            exception.printStackTrace();
            return Response.fail("5997","magina_Interrup_error",exception.getMessage());
        }
        log.error( exception.getMessage());
        exception.printStackTrace();
        return Response.fail("5999", "msg_system_error", exception.toString());
    }



}